package com.lv.suyiyong.hfr.fragment

import android.os.Bundle
import android.view.View
import androidx.databinding.ViewDataBinding
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.StaggeredGridLayoutManager
import com.blankj.utilcode.util.SizeUtils
import com.lv.common.base.BaseFragment
import com.lv.common.network.model.DataResult
import com.lv.common.utils.Constants
import com.lv.common.utils.MyUtils
import com.lv.common.widget.recyclerview.decoration.SpacesItemDecoration
import com.lv.service.bean.CompanyBean
import com.lv.service.bean.GoodsBean
import com.lv.service.bean.GoodsItemBean
import com.lv.service.model.ServiceViewModel
import com.lv.service.net.PageCategoryBody
import com.lv.service.network.BaseYgxRsp
import com.lv.service.network.onBizError
import com.lv.service.network.onBizOK
import com.lv.service.network.onFailure
import com.lv.service.network.onSuccess
import com.lv.suyiyong.hfr.R
import com.lv.suyiyong.hfr.adapter.HotSalerGoodsAdapter
import com.lv.suyiyong.hfr.databinding.FragmentCategoryHomeBinding
import com.scwang.smartrefresh.layout.api.RefreshLayout
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.withContext
import org.koin.androidx.viewmodel.ext.android.viewModel
import java.lang.reflect.Method

/**
 * 作者： ygx
 * 创建日期：2023/3/10 3:49 PM
 * 签名： 天行健，君子以自强不息；地势坤，君子以厚德载物。
 * -    _              _           _     _   ____  _             _ _
 * -   / \   _ __   __| |_ __ ___ (_) __| | / ___|| |_ _   _  __| (_) ___
 * -  / _ \ | '_ \ / _` | '__/ _ \| |/ _` | \___ \| __| | | |/ _` | |/ _ \
 * - / ___ \| | | | (_| | | | (_) | | (_| |  ___) | |_| |_| | (_| | | (_) |
 * -/_/   \_\_| |_|\__,_|_|  \___/|_|\__,_| |____/ \__|\__,_|\__,_|_|\___/
 * <p>
 * You never know what you can do until you try !
 * ----------------------------------------------------------------
 * 描述：热销 fragment
 */
class HotSalerGoodsFragment : BaseFragment() {
    private var page: Int = 1
    private var pageSize: Int = Constants.pageSize
    private var mFcaid: Int = 0
    private var mFristLoading = false
    private var mAdapter: HotSalerGoodsAdapter? = null
    private val mBenas = mutableListOf<GoodsItemBean>()
    private lateinit var mCheckForGapsMethod: Method
    private lateinit var mMarkItemDecorInsetsDirtyMethod: Method // StaggeredGridLayoutManager
    private val viewModelService: ServiceViewModel by viewModel()
    private val myScope: CoroutineScope = CoroutineScope(SupervisorJob())
    private var mBinding: FragmentCategoryHomeBinding? = null
    override fun getLayoutRes() = R.layout.fragment_category_home

    override fun bindView(view: View, savedInstanceState: Bundle?): ViewDataBinding {
        mBinding = FragmentCategoryHomeBinding.bind(view).apply {
        }
        return mBinding!!
    }


    override fun onResume() {
        super.onResume()
        if (!mFristLoading && isVisible) {
            mFristLoading = true
            mBinding?.refreshLayout?.autoRefresh()
        }
    }


    override fun initConfig() {
        super.initConfig()

    }


    override fun initData() {
        super.initData()
        arguments?.let {
            mFcaid = it.getInt("fcaid", 0)
        }
        initAdapter()

    }

    private fun initAdapter() {
        //反射获取StaggeredGridLayoutManager的checkForGaps方法
        mCheckForGapsMethod =
            StaggeredGridLayoutManager::class.java.getDeclaredMethod("checkForGaps")
        mCheckForGapsMethod.isAccessible = true
        //反射获取RecyclerView的MarkItemDecorInsetsDirty方法
        mMarkItemDecorInsetsDirtyMethod =
            RecyclerView::class.java.getDeclaredMethod("markItemDecorInsetsDirty")
        mMarkItemDecorInsetsDirtyMethod.isAccessible = true
        val layoutManager = StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL)
        mBinding?.rvContent?.layoutManager = layoutManager
        //防止item乱跳错位 防止item 交换位置
        mBinding?.rvContent?.itemAnimator = null
        mAdapter = HotSalerGoodsAdapter(mBenas)
        mBinding?.rvContent?.adapter = mAdapter
        mBinding?.rvContent?.addItemDecoration(
            SpacesItemDecoration(
                SizeUtils.dp2px(10.0f),
                SizeUtils.dp2px(10.0f),
                false
            )
        )

    }


//    private suspend fun refreshFactoryBanner() {
//        withContext(Dispatchers.IO) {
//            myScope.async {
//                mFactoryBannerAdapter?.notifyDataSetChanged()
//            }.await()
//        }
//    }


    private fun salehot() {
        val body =
            PageCategoryBody(page, pageSize, mFcaid, "")
        lifecycleScope.launchWhenCreated {
            val result: DataResult<BaseYgxRsp> =
                withContext(myScope.coroutineContext) {
                    viewModelService.salehot(body)
                }
            parseResult(result)
        }
    }

    private fun parseResult(data: DataResult<BaseYgxRsp>) {
        loadFinished()
        data.onSuccess {
            onBizOK<GoodsBean> { code, data, message, result ->
                val items = data?.items
                MyUtils.recyclerviewSetData(
                    page, pageSize, mBinding?.refreshLayout, mBenas, items, mAdapter
                )
                if (mBenas.isEmpty()) {
                    mAdapter?.setEmptyView(getEmptyView(mBinding?.rvContent!!))
                }

            }
            onBizError<CompanyBean> { code, message, data ->
                loadFinished()
                mBinding?.refreshLayout?.finishRefresh()
                mBinding?.refreshLayout?.finishLoadMore()
            }
        }
        data.onFailure {
            loadFinished()
            mBinding?.refreshLayout?.finishRefresh()
            mBinding?.refreshLayout?.finishLoadMore()
        }
    }

    override fun initEvents() {
        super.initEvents()
        mBinding?.refreshLayout?.setOnRefreshLoadMoreListener(object : OnRefreshLoadMoreListener {
            override fun onRefresh(refreshLayout: RefreshLayout) {
                page = 1
                salehot()
            }

            override fun onLoadMore(refreshLayout: RefreshLayout) {
                page++
                salehot()
            }
        })
    }

    /**
     * 初始化轮播图Adapter
     */
    private fun initBannerAdapter() {
//        mFactoryBannerAdapter = BannerHomeFactoryAdapter(mFacBanners)
//        mBannerFactory?.adapter = mFactoryBannerAdapter
//        mBrandBannerAdapter = BannerHomeBrandAdapter(mBrandBeans)
//        mBannerBrand?.adapter = mBrandBannerAdapter
//        mLocationBannerAdapter = BannerHomeBrandAdapter(mLocationBeans)
//        mBannerLocation?.adapter = mLocationBannerAdapter
//
//        mBannerAdapter = object : BannerImageAdapter<AdItemBean>(mBannerDatas) {
//            override fun onBindView(
//                holder: BannerImageHolder?,
//                data: AdItemBean?,
//                position: Int,
//                size: Int
//            ) {
//                Glide.with(requireContext())
//                    .load(data?.image)
//                    .into(holder?.imageView!!)
//            }
//        }
//        mBannerHeader?.adapter = mBannerAdapter

    }

    /**
     * 设置Banner适配器
     */
//    private fun bannerObserver() {
//
//        mBannerFactory?.addBannerLifecycleObserver(viewLifecycleOwner)
//            ?.setAdapter(mFactoryBannerAdapter)
//            ?.setIntercept(true)
//
//        mBannerBrand?.addBannerLifecycleObserver(viewLifecycleOwner)
//            ?.setAdapter(mBrandBannerAdapter)
//            ?.setIntercept(true)
//
//        mBannerLocation?.addBannerLifecycleObserver(viewLifecycleOwner)
//            ?.setAdapter(mLocationBannerAdapter)
//            ?.setIntercept(true)
//
//
//        mBannerHeader?.addBannerLifecycleObserver(viewLifecycleOwner)
//            ?.setAdapter(mBannerAdapter)
//            ?.setIntercept(true)
//
//    }

    companion object {
        fun newInstance(fcaid: Int): HotSalerGoodsFragment {
            val args = Bundle()
            args.putInt("fcaid", fcaid)
            val fragment = HotSalerGoodsFragment()
            fragment.arguments = args
            return fragment
        }
    }


}